﻿using Arim.S4.Api;
using Arim.S4.Client.Base.Dto;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Arim.S4.Client.Service
{
    public abstract class BaseAppService<T> : BaseAppService<T, QueryDto>, IAppService
       where T : EntityDto, new()
    {
        public BaseAppService(string path) : base(path)
        {
        }
    }

    public abstract class BaseAppService<T, TQuery> : IAppService
    where T : EntityDto, new()
    where TQuery : class, IQueryDto
    {
        public virtual RestApi<T> RestApi { get; set; }
        public virtual RestApi<P> BuildRestApi<P>() where P : class, new()
        {
            return new RestApi<P>();
        }
        public virtual string Path { get; set; }
        public BaseAppService(string path)
        {
            this.RestApi = new RestApi<T>(ConfigurationManager.AppSettings.Get("ApiBaseUrl"));
            this.Path = path;
        }
        public virtual IList<T> GetAll(string path, TQuery query = null)
        {
            return this.RestApi.GetAll(path, query);
        }

        public virtual IList<T> GetAll(TQuery query = null)
        {
            return this.RestApi.GetAll(this.Path, query);
        }

        public virtual PagedList<T> GetPagedList(PageDto pager, TQuery query = null)
        {
            return this.RestApi.GetPagedList(this.Path, pager, query);
        }

        public virtual T Get(long id)
        {
            return this.RestApi.Get(this.Path + string.Format("/{0}", id), null);
        }

        public virtual T Insert(T dto)
        {
            return this.RestApi.Post(this.Path, dto);
        }

        public virtual T InsertOrUpdate(T dto)
        {
            if (dto.Id != 0)
                return this.Update(dto);
            return this.Insert(dto);
        }

        public virtual T Update(T dto)
        {
            return this.RestApi.Put(this.Path + string.Format("/{0}", dto.Id), dto);
        }

        public virtual void Delete(long id)
        {
            this.RestApi.Delete(this.Path + string.Format("/{0}", id), null);
        }
    }
}
